package com.yn.pet.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yn.pet.bus.dao.DeviceInfoDao;
import com.yn.pet.bus.entity.AlarmRecord;
import com.yn.pet.bus.entity.DeviceInfo;
import com.yn.pet.bus.entity.DeviceSyncSettings;
import com.yn.pet.bus.entity.LocationRealtime;
import com.yn.pet.bus.enums.DeviceStatusEnum;
import com.yn.pet.web.service.AlarmRecordService;
import com.yn.pet.web.service.DeviceInfoService;
import com.yn.pet.web.service.DeviceSyncSettingsService;
import com.yn.pet.web.service.LocationRealtimeService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Slf4j
@Service
@AllArgsConstructor
public class DeviceInfoServiceImpl extends ServiceImpl<DeviceInfoDao, DeviceInfo> implements DeviceInfoService {

    private final AlarmRecordService alarmRecordService;
    private final DeviceSyncSettingsService deviceSyncSettingsService;
    private final LocationRealtimeService locationRealtimeService;

    @Transactional
    public void deviceOffline(String imei) {
        log.info("设备离线{}", imei);
        DeviceInfo deviceInfo = this.list(new LambdaQueryWrapper<DeviceInfo>().eq(DeviceInfo::getImei, imei)).stream().findAny().orElse(null);
        if (deviceInfo != null){
            deviceInfo.setDeviceStatus(DeviceStatusEnum.OFFLINE.getCode());
            deviceInfo.setStatusChangeTime(new Date());
            this.updateById(deviceInfo);
            DeviceSyncSettings deviceSyncSettings = deviceSyncSettingsService.list(new LambdaQueryWrapper<DeviceSyncSettings>().eq(DeviceSyncSettings::getDeviceId, deviceInfo.getDeviceId())).stream().findAny().orElse(null);
            if (deviceSyncSettings !=null && deviceSyncSettings.getOfflineEnabled() == 1){
                LocationRealtime realtime = locationRealtimeService.getLatestLocationByDeviceId(deviceInfo.getDeviceId());
                AlarmRecord alarmRecord = new AlarmRecord();
                alarmRecord.setDeviceId(deviceInfo.getDeviceId());
                alarmRecord.setType(3);
                alarmRecord.setLocationId(realtime.getLocationId());
                alarmRecord.setCreateTime(new Date());
                alarmRecord.setUpdateTime(new Date());
                alarmRecordService.save(alarmRecord);
            }
        }

    }
}
